class Dept < ActiveRecord::Base
  
  validates :name, :link_phone, :link_man, :address, :presence => true
  validates :name, :uniqueness => true
  
  has_many :furnitures
  has_many :furniture_logistic_stats
  has_many :posts

  scope :visible, where('status = ?','visible')
  
  def self.stored_furnitures_by_key_word(key_word)
    FurnitureLogisticStat.where('(materials.name like :key_word or materials.code like :key_word or factories.name like :key_word or furniture_styles.code like :key_word or furniture_styles.code like :key_word) and furniture_logistic_stats.stored_count > 0  ',{ :key_word => key_word}).includes(
      :furniture => [
        :material,
        { :furniture_style => :factory }
      ]      
    )
  end
  
  def self.stored_furnitures_count_by_key_word(key_word)
    stored_furnitures_by_key_word(key_word).each_with_object([]) do |stat, counts|
      counts << stat.stored_count
    end.sum
  end
  
  def stored_furnitures_by_key_word(key_word)
    FurnitureLogisticStat.where('(materials.name like :key_word or materials.code like :key_word or factories.name like :key_word or furniture_styles.code like :key_word or furniture_styles.code like :key_word) and furniture_logistic_stats.dept_id = :dept_id and furniture_logistic_stats.stored_count > 0  ',{ :key_word => key_word, :dept_id => id}).includes(
      :furniture => [
        :material,
        { :furniture_style => :factory }
      ]      
    )
  end
  
  def stored_furnitures_count_by_key_word(key_word)
    stored_furnitures_by_key_word(key_word).each_with_object([]) do |stat, counts|
      counts << stat.stored_count
    end.sum
  end

  def visible!
    update_attribute :status, 'visible'
  end

  def hidden!
    update_attribute :status, 'hidden'
  end

  def status
    ActiveSupport::StringInquirer.new(self[:status])
  end
end
